package com.frank.stock4j.dataloader.service;

import com.frank.stock4j.dataloader.abstractloader.AbstractLoader;
import com.frank.stock4j.dataloader.common.ApplicationContextProvider;
import com.frank.stock4j.dataloader.configuration.TuShareConfig;
import com.frank.stock4j.dataloader.constant.CommonConstants;
import com.frank.stock4j.tusharepro.BaseBean;
import com.frank.stock4j.tusharepro.TusharePro;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class LoadDataService {
    @Autowired
    TuShareConfig config;
    @Autowired
    ApplicationContextProvider contextProvider;

    boolean inited = false;

    public void init() {
        if (inited) {
            return;
        }
        TusharePro.setGlobal(new TusharePro.Builder()
                .setToken(config.getToken())  // 你的token
                .build());  // 设置全局配置
        inited = true;
    }

    @SneakyThrows
    public List<BaseBean> load(String beanName) {
        init();
        String className = CommonConstants.LOADER_PACKAGE.replace("{className}", beanName);
        Class cls = Class.forName(className);
        AbstractLoader abstractLoader = (AbstractLoader)ApplicationContextProvider.getBean(cls);
        return abstractLoader.load();
    }

    @SneakyThrows
    public void stop(String beanName) {
        String className = CommonConstants.LOADER_PACKAGE.replace("{className}", beanName);
        Class cls = Class.forName(className);
        AbstractLoader abstractLoader = (AbstractLoader)ApplicationContextProvider.getBean(cls);
        abstractLoader.stop();
        log.info("bean:{} has been stoped", cls.getName());
    }
}
